//------------------------------------------------------------------------------
//  <copyright file="SLAM2DAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//  </copyright>
//------------------------------------------------------------------------------

namespace Microsoft.Robotics.Navigation.Runtime.Localization
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Runtime.Serialization;
    using Microsoft.Robotics.Hardware.DAC;
    using Microsoft.Robotics.Hardware.Runtime.DAC;
    using Microsoft.Robotics.IO;
    using Microsoft.Robotics.Navigation.Localization;
    using Microsoft.Robotics.Navigation.Motion;
    using Microsoft.Robotics.Navigation.Perception;
    using Microsoft.Robotics.Navigation.Runtime.Localization;
    using Microsoft.Robotics.Numerics;
    using Microsoft.Robotics.Runtime;

    /// <summary>
    /// Agent that creates and maintains a global map while determining the robot location on that map.
    /// </summary>
    /// <typeparam name="TObservation">The horizontal depth profile observation</typeparam>
    /// <typeparam name="TDriveFeedbackState">The drive feedback state type used for motion update</typeparam>
    [DataContract]
    public class SLAM2DAgent<TObservation, TDriveFeedbackState> : ParticleFilterLocalizationAgent<SLAM2DParticleFilter<TObservation, TDriveFeedbackState>, SLAM2DParticle, TObservation, SLAM2DAgentMessage, TDriveFeedbackState>, IMessagePublisher<HDPwithPoseMessage<TObservation>>
        where TObservation : IHorizontalDepthProfile
        where TDriveFeedbackState : IDriveState
    {
        /// <summary>
        /// The default height of the global map (in pixel)
        /// </summary>
        private const int DefaultHeight = 800;

        /// <summary>
        /// The default width of the global map (in pixel)
        /// </summary>
        private const int DefaultWidth = 800;

        /// <summary>
        /// The default number of messages posted before the most likely
        /// particle is copied over to all other particles
        /// </summary>
        private const int DefaultFrameCutOff = 10;

        /// <summary>
        /// The number of frames between particle collapse
        /// </summary>
        [DataMember(Name = "FramesToCollapse")]
        private int framesToCollapse;

        /// <summary>
        /// The height of the global map to create.
        /// </summary>
        [DataMember(Name = "MapHeight")]
        private int mapHeight;

        /// <summary>
        /// The width of the global map to create.
        /// </summary>
        [DataMember(Name = "MapWidth")]
        private int mapWidth;

        /// <summary>
        /// The publishing port for the hdp messages
        /// </summary>
        private IForwarder<HDPwithPoseMessage<TObservation>> hdpWithPoseMessagePublisher;

        /// <summary>
        /// Counter of the $HDPWithPoseMessages$
        /// </summary>
        private int messageCounter;

        /// <summary>
        /// Initializes a new instance of the SLAM2DAgent class
        /// </summary>
        /// <param name="name">Agent name</param>
        /// <param name="hdpProducer">Producer to subscribe to</param>
        /// <param name="driveFeedbackProducer">Drive feedback producer to subscribe to</param>
        /// <param name="robotConfigFolder">The robot config folder.</param>
        /// <param name="distanceResolution">The actual distance resolution.</param>
        /// <param name="particleCount">The number of particles for the particle filter.</param>
        /// <param name="mapHeight">The height of the global map to create.</param>
        /// <param name="mapWidth">The width of the global map to create.</param>
        /// <param name="mapFile">The map to load.</param>
        /// <param name="robotStartPose">The starting pose of the robot, if known</param>
        /// <param name="frameCutoff">The number of frames in between particle collapse (-1 for infinite)</param>
        public SLAM2DAgent(
            string name,
            IProducer<SimpleAgentMessage<TObservation>> hdpProducer,
            IProducer<SimpleAgentMessage<TDriveFeedbackState>> driveFeedbackProducer,
            string robotConfigFolder,
            float distanceResolution,
            int particleCount,
            int mapHeight,
            int mapWidth,
            string mapFile,
            Pose2D robotStartPose,
            int frameCutoff = DefaultFrameCutOff)
            : base(name, hdpProducer, driveFeedbackProducer, robotConfigFolder, distanceResolution, particleCount, mapFile, robotStartPose, new Pose2D(0, 0, 0))
        {
            this.mapHeight = mapHeight;
            this.mapWidth = mapWidth;
            this.framesToCollapse = frameCutoff;
        }

        /// <summary>
        /// Called to store the forwarder for the given type we want to publish
        /// </summary>
        /// <param name="forwarder">The forwarder to use when publishing</param>
        public void InitializePublisher(IForwarder<HDPwithPoseMessage<TObservation>> forwarder)
        {
            this.hdpWithPoseMessagePublisher = forwarder;
        }

        /// <summary>
        /// Initialize the agent
        /// </summary>
        /// <param name="locator">The agent locator</param>
        public override void Initialize(AgentLocator locator)
        {
            if (this.mapHeight == 0)
            {
                this.mapHeight = DefaultHeight;
            }

            if (this.mapWidth == 0)
            {
                this.mapWidth = DefaultWidth;
            }
            
            base.Initialize(locator);
        }

        /// <summary>
        /// Called on activation
        /// </summary>
        public override void OnActivated()
        {
            base.OnActivated();
            this.messageCounter = 0;
        }

        /// <summary>
        /// Called when the agent transitions from active to inactive.
        /// </summary>
        public override void OnDeactivated()
        {
            // save the map file if a map file path is provided
            if (this.MapFile != null)
            {
                Serializer.Save(this.MapFile, this.Filter.GetHighestLikelihoodParticle().Map);
            }

            base.OnDeactivated();
        }

        /// <summary>
        /// Creates the underlying particle filter used to estimate the pose and the map.
        /// </summary>
        /// <param name="map">The map to start with.</param>
        /// <param name="distanceResolution">The resolution of the map</param>
        /// <param name="robotStartPose">The initial pose</param>
        /// <returns>The message to publish</returns>
        protected override SLAM2DParticleFilter<TObservation, TDriveFeedbackState> CreateFilter(GlobalMap map, float distanceResolution, Pose2D robotStartPose)
        {
            if (map == null)
            {
                map = new GlobalMap(this.mapWidth, this.mapHeight, robotStartPose, distanceResolution);
            }

            return new SLAM2DParticleFilter<TObservation, TDriveFeedbackState>(map, this.ParticleCount, robotStartPose);
        }

        /// <summary>
        /// Creates a new message to publish, based on the agent state. Called every time the filter is updated.
        /// </summary>
        /// <param name="observationMessage">The latest observation (HDP)</param>
        /// <returns>The message to publish</returns>
        protected override SLAM2DAgentMessage CreateMessage(SimpleAgentMessage<TObservation> observationMessage)
        {
            // Send trajectory of most likely particle
            SLAM2DParticle likelyParticle = this.Filter.GetHighestLikelihoodParticle();
            HDPwithPoseMessage<TObservation> message = new HDPwithPoseMessage<TObservation>(likelyParticle.Map.MapCellsToMeters(likelyParticle.Pose), observationMessage.State, this.messageCounter, observationMessage);
            this.hdpWithPoseMessagePublisher.Post(message, true);
            this.messageCounter++;

            Pose2D[] poses = new Pose2D[this.ParticleCount];
            Pose2D mapStartPose = this.Filter.Particles[0].Map.MapStartPose;
            for (int i = 0; i < this.ParticleCount; i++)
            {
                poses[i] = this.GetPoseInGlobalCoordinates(this.Filter.Particles[i].Pose, mapStartPose);
            }

            Pose2D likelyPose = this.GetPoseInGlobalCoordinates(likelyParticle.Pose, mapStartPose);

            // TODO: add map resolution to message, and figure out how not to break path planning
            SLAM2DParticle[] particles = (SLAM2DParticle[])this.Filter.Particles.Clone();
            SLAM2DAgentMessage newMessage = new SLAM2DAgentMessage(likelyParticle.Map, likelyPose, poses, particles, observationMessage);
            return newMessage;
        }
    }
}
